using System.ComponentModel;
using System.Windows.Threading;
using System.Threading;
using System.Windows;

namespace MefBasic.Threading
{
    public class BackgroundWorkerEx : BackgroundWorkerWrapper, IBackgroundWorkerEx
    {
        protected override void OnProgressChanged(ProgressChangedEventArgs e)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(InvokeProcessChanged), e);
        }

        private void InvokeProcessChanged(object parameter)
        {
            var e = (ProgressChangedEventArgs)parameter;
            base.OnProgressChanged(e);
        }
        protected override void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
        {
            InvokeRunWorkerCompleted(e);
        }

        private void InvokeRunWorkerCompleted(object parameter)
        {
            var e = (RunWorkerCompletedEventArgs)parameter;
            base.OnRunWorkerCompleted(e);
            IsWorkerBusy = false;
        }
        public void RunWorkerBlocked()
        {
            IsWorkerBusy = true;
            RunWorkerAsync();
            Block();
        }

        public void Block()
        {
            if (Application.Current == null)
                return;
            while (IsWorkerBusy)
            {
                DoEvents();
            }
        }

        private static void DoEvents()
        {
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
        }

        public void RunWorkerBlocked(object parameter)
        {
            IsWorkerBusy = true;
            RunWorkerAsync(parameter);
            if (Application.Current == null)
                return;
            while (IsWorkerBusy)
                DoEvents();
        }
    }
}